//  http://tinymce.ax-z.cn/   中文文档

layui.define(['jquery'],function (exports) {
    var $ = layui.$

    var modFile = layui.cache.modules['tinymce'];

    var modPath = modFile.substr(0, modFile.lastIndexOf('.'))

    var setter = layui.setter || {}//兼容layuiadmin

    var response = setter.response || {}//兼容layuiadmin

    //  ----------------  以上代码无需修改  ----------------

    var plugin_filename = 'tinymce.min.js'//插件路径，不包含base_url部分

    var settings = {
        base_url: modPath
        , images_upload_url: ''//图片上传接口，可在option传入，也可在这里修改，option的值优先
        , language: 'zh_CN'//语言，可在option传入，也可在这里修改，option的值优先
        , response: {//后台返回数据格式设置
            statusName: response.statusName || 'code'//返回状态字段
            , msgName: response.msgName || 'msg'//返回消息字段
            , dataName: response.dataName || 'data'//返回的数据
            , statusCode: response.statusCode || {
                ok: 0//数据正常
            }
        }
        , success: function (res, succFun, failFun) {//图片上传完成回调 根据自己需要修改
            if (res[this.response.statusName] == this.response.statusCode.ok) {
                succFun(res[this.response.dataName]);
            } else {
                failFun(res[this.response.msgName]);
            }
        }
    };

    //  ----------------  以下代码无需修改  ----------------

    var t = {};

    //初始化
    t.render = function (option,callback) {

        var admin = layui.admin || {}

        var form = option.form || {}

        var file_field = form.name || 'edit' //文件字段名

        var form_data = form.data || {} //其他表单数据 {key:value, ...}

        option.suffix= isset(option.suffix) ? option.suffix : (plugin_filename.indexOf('.min')>-1 ? '.min' : '')

        option.base_url = isset(option.base_url) ? option.base_url : settings.base_url

        option.language = isset(option.language) ? option.language : settings.language

        option.lineheight_formats = '1 1.1 1.2 1.3 1.5 1.6 1.7 1.8 2 2.1 2.3 2.5';

        option.fontsize_formats = '8px 8pt 12px 12pt 14px 14pt 16px 16pt 18px 18pt 24px 24pt 36px 36pt 48px 48pt 56px 56pt 72px 72pt';

        option.font_formats = '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;';
        option.toolbar_mode = 'wrap';  // 工具栏始终可见
        option.selector = isset(option.selector) ? option.selector : option.elem

        option.quickbars_selection_toolbar = isset(option.quickbars_selection_toolbar) ? option.quickbars_selection_toolbar : 'cut copy | bold italic underline strikethrough '

        option.plugins = isset(option.plugins) ? option.plugins : 'quickbars print preview searchreplace autolink fullscreen image link media codesample table charmap hr advlist lists wordcount imagetools indent2em code letterspacing layout';

        option.toolbar = isset(option.toolbar) ? option.toolbar : 'undo redo | lineheight |forecolor backcolor bold italic underline strikethrough | indent2em alignleft aligncenter alignright alignjustify outdent indent | link bullist numlist image table codesample | formatselect fontselect fontsizeselect letterspacing layout';
        option.resize = isset(option.resize) ? option.resize : false;
        option.letterspacing = "0px 1px 2px 3px 4px 5px 6px 7px 8px 10px 12px 15px 20px 24px";
        option.table_icons = {// 以下下为默认配置
            'align-right-table': '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm6 4h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2zm-6-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2z" fill-rule="evenodd"></path></svg>',
            'align-left-table': '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm0 4h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2zm0-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2z" fill-rule="evenodd"></path></svg>',
            'align-center-table': '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 1 1 0-2zm3 4h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 1 1 0-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 0 1 0-2zm-3-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 0 1 0-2z" fill-rule="evenodd"></path></svg>'
        };
        option.layout_options = {
            style: {
                'text-align': 'justify',
                'text-indent': '2em',
                'line-height': 1.5
            },
            filterTags: ['table>*', 'tbody'], //'table，'tbody','td','tr' 将会忽略掉 同时 table>*，忽略table 标签 以及所有子标签
            clearStyle: ['text-indent'],//text-indent 将会被清除掉
            tagsStyle: {
                'table': {
                    'line-height': 3,
                    'text-align': 'center'
                },
                'table,tbody,tr,td': { //支持并集选择
                    'line-height': 2
                },
                'tr>td,table>tbody': { //支持, 精准定位 通过 ' > '
                    'line-height': 3,
                    'text-align': 'center'
                }
            }
        };
        option.elementpath = isset(option.elementpath) ? option.elementpath : false;

        option.branding = isset(option.branding) ? option.branding : false;

        option.contextmenu_never_use_native = isset(option.contextmenu_never_use_native) ? option.contextmenu_never_use_native : true;

        option.menubar = isset(option.menubar) ? option.menubar : 'file edit insert format table';

        option.images_upload_url = isset(option.images_upload_url) ? option.images_upload_url : settings.images_upload_url;

        option.images_upload_handler = isset(option.images_upload_handler) ? option.images_upload_handler : function (blobInfo, succFun, failFun) {

            if(isEmpty(option.images_upload_url)){
                
                failFun("上传接口未配置");
                
                return console.error('images_upload_url未配置');
            
            }

            var formData = new FormData();

            formData.append(file_field, blobInfo.blob());

            if(typeof form_data == 'object'){
            
                for(var key in form_data){
            
                    formData.append(key, form_data[key]);
            
                }
            
            }

            var ajaxOpt = {

                url: option.images_upload_url,

                dataType: 'json',

                type: 'POST',

                data: formData,

                processData: false,

                contentType: false,

                success: function (res) {

                    settings.success(res, succFun, failFun)

                },
                error: function (res) {

                    failFun("网络错误：" + res.status);

                }
            };

            if (typeof admin.req == 'function') {

                admin.req(ajaxOpt);

            } else {

                $.ajax(ajaxOpt);

            }
        }

        var edit = t.get(option.elem);

        if (edit) {

            edit.destroy();

        }

        option.menu = isset(option.menu) ? option.menu : {

            file: {title: '文件', items: 'newdocument | print preview fullscreen | wordcount'},

            edit: { title: '编辑', items: 'undo redo | cut copy paste pastetext selectall | searchreplace | code'},

            format: {

                title: '格式',

                items: 'bold italic underline strikethrough superscript subscript | formats | lineheight | forecolor backcolor | removeformat',
           
            },
            
            table: {title: '表格', items: 'inserttable tableprops deletetable | cell row column'},
          
        };
        
        initTinymce();

        layui.sessionData('layui-tinymce',{

            key:option.selector,

            value:option
        })

        tinymce.init(option);

        if(typeof callback == 'function'){
            callback.call(option)
        }

        return tinymce.activeEditor;
    };

    t.init = t.render

    // 获取ID对应的编辑器对象
    t.get = function (elem) {

        initTinymce();

        if (elem && /^#|\./.test(elem)) {

            var id = elem.substr(1);

            var edit = tinymce.editors[id];
            
            return edit

        } else {
            return false;
        }
    }

    //重载
    t.reload = function (option,callback) {

        option = option || {}

        var edit = t.get(option.elem);

        var optionCache = layui.sessionData('layui-tinymce')[option.elem]

        edit.destroy()

        $.extend(optionCache,option)

        tinymce.init(optionCache)

        if(typeof callback == 'function'){
            callback.call(optionCache)
        }

        return tinymce.activeEditor;
    }

    // 适配单页应用的渲染
    t.autoRender = function (option, callback) {

        if (typeof tinymce == 'undefined') {
            return t.render(option, callback);
        }

        if (!tinymce.editors[option.elem.substr(1)]) {
            return t.render(option, callback);
        }

        return t.reload(option, callback);
    }

    function initTinymce(){
        if (typeof tinymce == 'undefined') {
            $.ajax({//获取插件
                url: settings.base_url + '/' + plugin_filename,
                dataType: 'script',
                cache: true,
                async: false,
            });
        }
    }

    function isset(value){
        return typeof value !== 'undefined' && value !== null
    }

    function isEmpty(value){
        if(typeof value === 'undefined' || value === null|| value === ''){
            return true
        } else if (value instanceof Array && value.length === 0){
            return true
        } else if (typeof value === 'object' && Object.keys(value).length === 0){
            return true
        }
        return false
    }

    exports('tinymce', t);

});

function autoImportImage(editor, catalogue) {
    // 粘贴远程图片本地化
    editor.on('paste', (e) => {
        setTimeout(function () {
            let remoteImages = [];
            const doc = editor.getDoc();
            const items = doc.getElementsByTagName('img');
            if (items.length) {
                var i = 1;
                for (img of items) {
                    $(img).attr("id", "ImgId_" + generateGuid())
                    var src = img.getAttribute('_src') || img.src || '';
                    var ImgId = img.getAttribute('id') || img.src || '';
                    const obj = {}
                    obj.url = src
                    obj.source = ImgId
                    remoteImages.push(obj);
                }
            }
            if (remoteImages.length) {
                //需要上传的图片
                $.ajax({
                    url: '/api/file/AutoImportEditorImage', // 接收远程图片抓去的后端地址
                    method: 'post',
                    data: { images: remoteImages, catalogue: catalogue },
                    success: function (res) {
                        var data = res;
                        if (data.code == 200) {
                            console.log(data.result)
                            let i, o, item, res, _id, __src, list = data.result;
                            for (i = 0; item = items[i++];) {
                                _id = item.getAttribute('id') || item.id || '';
                                for (o = 0; res = list[o++];) {
                                    if (_id == res.source && res.code == 200) {// 抓取失败时不做替换处理
                                        __src = res.url;
                                        replaceImage(item, res, editor); // 使用下面的新方法
                                        break;
                                    }
                                }
                            }
                            // 同步到textarea
                            editor.save();
                        }
                    }
                });
            }
        }, 100);
    });
}

function replaceImage(image, data, editor) {
    const each = function (xs, f) {
        for (var i = 0, len = xs.length; i < len; i++) {
            var x = xs[i];
            f(x, i);
        }
    };
    const map = function (xs, f) {
        var len = xs.length;
        var r = new Array(len);
        for (var i = 0; i < len; i++) {
            var x = xs[i];
            r[i] = f(x, i);
        }
        return r;
    };
    const replaceString = function (content, search, replace) {
        let index = 0;
        do {
            index = content.indexOf(search, index);
            if (index !== -1) {
                content = content.substring(0, index) + replace + content.substr(index + search.length);
                index += replace.length - search.length + 1;
            }
        } while (index !== -1);
        return content;
    };
    const replaceImageUrl = function (content, targetUrl, replacementUrl) {
        let replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === '' ? ' data-placeholder="1"' : '');
        content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
        return content;
    };
    const replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
        each(editor.undoManager.data, function (level) {
            if (level.type === 'fragmented') {
                level.fragments = map(level.fragments, function (fragment) {
                    return replaceImageUrl(fragment, targetUrl, replacementUrl);
                });
            } else {
                level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
            }
        });
    };
    let src = editor.convertURL(data.url, 'src');
    let attr = {
        'src': data.url,
        'data-app': "news",
        'data-aid': 190
    };
    replaceUrlInUndoStack(image.src, data.url);
    editor.$(image).attr(attr).removeAttr('alt').removeAttr('data-mce-src');
}

function generateGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
